package com.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.dao.UsersDAO;
import com.model.Users;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ModelDriven;

public class UsersAction implements ModelDriven<Users>{

	private Users users;

	UsersDAO usersDAO=new UsersDAO();
	HttpServletRequest request=ServletActionContext.getRequest();
	public String login() {
		Users u=usersDAO.get(users.getUsername(),users.getPassword());
		if (u!=null) {
			ActionContext atx=ActionContext.getContext();
			Map<String,Object> session=atx.getSession();
			session.put("loginUser", u);
			return "success";
		} else {
			return "login";
		}
	}

	public String add() {
		users.setRoleId(2);
		usersDAO.save(users);
		return "success";
	}
	public String delete() {
	   	String sid=request.getParameter("id");
	   	usersDAO.delete(Integer.parseInt(sid));
		return "success";
	}

	public String edit() {
		String sid = (String) request.getParameter("id");
		Users user = usersDAO.get(Integer.parseInt(sid));
		request.setAttribute("user", user);
		return "success";
	}
	public String update() {
		usersDAO.update(users);
		return "success";
	}

	public String show() {
		List<Users> userslist = usersDAO.getAll();
		request.setAttribute("userslist", userslist);
		return "success";
	}
	
	public String loginOut() {
		ActionContext atx=ActionContext.getContext();
		Map<String,Object> session=atx.getSession();
		session.remove("loginUsers");
		return "success";
	}

	@Override
	public Users getModel() {
		users=new Users();
		return users;
	}

}
